import { Component, OnDestroy, OnInit } from '@angular/core';
import { Store } from '@ngxs/store';
import { SystemAction, SystemSelector } from '../../../store';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ResetForm } from '@ngxs/form-plugin';
import { NzMessageService } from 'ng-zorro-antd/message';
import { UserAction } from '../../../store/user';
import { Subject, takeUntil } from 'rxjs';

@Component({
  selector: 'app-information',
  templateUrl: './information.component.html',
  styleUrls: ['./information.component.scss'],
})
export class InformationComponent implements OnInit, OnDestroy {
  validateForm: FormGroup;
  dictionary$ = this.store.select(SystemSelector.dictionary);
  ngxsFormKey = 'system.userInfoForm';
  destroy = new Subject<void>();

  constructor(
      private store: Store,
      private fb: FormBuilder,
      private message: NzMessageService,
  ) {
    this.validateForm = this.fb.group({
      email: ['', [Validators.email]],
      name: [''],
      gender: [''],
    });
    this.store.select(SystemSelector.user).pipe(takeUntil(this.destroy)).subscribe(r => {
      this.store.dispatch(new ResetForm({path: this.ngxsFormKey, value: r}));
    });
  }

  ngOnDestroy(): void {
    this.destroy.next();
  }

  ngOnInit(): void {
  }

  submitForm() {
    this.store.dispatch(new SystemAction.ModifyUserInfo()).subscribe(() => {
      this.message.success(`保存成功`);
    });
  }

  passwordModal() {
    this.store.dispatch(new UserAction.PasswordModal());
  }
}
